<template>
    <div class="tr">
        <div class="tr-top">
            <div class="left">
                <!-- <div class="itm"><el-button @click="addEv">新增</el-button></div> -->
                <!-- <div class="itm" v-if="timerConfig.status == false"><el-button
                        @click="timerTaskConfigEdit">启动</el-button>
                </div>
                <div class="itm" v-else><el-button @click="timerTaskConfigEdit">停止</el-button></div> -->
                <!-- <div class="itm"><el-button @click="timerTaskConfigEdit">保存</el-button>
                </div> -->
                <!-- <div class="itm"><el-input-number v-model="timerConfig.time" :step="1" step-strictly /></div> -->
                <div class="itm"><el-button @click="logItmEv('')">历史记录</el-button></div>
            </div>
            <div class="right">
                <div>
                    <el-select style="width: 120px" v-model="orderType" class="m-2" placeholder="Select" size="large">
                        <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
                <div class="itm" v-if="routeName == 'timertask'"> <el-input clearable v-model="tableObjData.type__like"
                        style="width: 240px" placeholder="输入类型" /></div>
                <div class="itm"> <el-input clearable v-model="tableObjData.name__like" style="width: 240px"
                        placeholder="输入名称" /></div>
                <div class="itm"><el-button @click="getEv(true)">查询</el-button></div>

            </div>
        </div>
        <div class="table-content">
            <el-table empty-text="暂无数据" border height="100%" :data="tableListData">
                <el-table-column align="center" type="index" label="#" width="50" />
                <el-table-column align="center" header-align="center" prop="name" label="名称" width="150" />
                <el-table-column v-if="routeName == 'timertask'" align="center" header-align="center" prop="type"
                    label="类型" width="120" />
                <el-table-column align="center" header-align="center" prop="rem" label="说明" width="250" />
                <!-- <el-table-column align="center" header-align="center" prop="create_time" label="创建时间" width="180" /> -->
                <el-table-column align="center" header-align="center" label="单据类型" width="120">
                    <template #default="scope">
                        <el-tag v-if="scope.row.order_type == 1" type="warning">基础数据</el-tag>
                        <el-tag v-else type="success">业务单据</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" header-align="center" label="操作" width="180">
                    <template #default="scope">
                        <!-- <el-button link type="primary" size="small" @click="updateSelRowEv(scope.row.id)">
                            编辑
                        </el-button> -->
                        <el-button v-if="scope.row.status == 1" link type="primary"
                            @click="timerTaskStatusEv(scope.row.id)" size="small">停止任务</el-button>
                        <el-button v-else @click="timerTaskStatusEv(scope.row.id)" link type="primary"
                            size="small">启动任务</el-button>
                        <el-button link type="primary" size="small" @click="logItmEv(scope.row.name)">
                            历史记录
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <pagination v-show="tableObjData.total > 0" :total="tableObjData.total" v-model:page="tableObjData.page"
            v-model:limit="tableObjData.pageSize" @pagination="getEv(true)" />

        <!-- 日志 -->
        <el-drawer @opened="openedDrawerEv" :size="'50%'" :close-on-click-modal="false" v-model="drawer" title="历史查询">
            <div style="height: 100%;width: 100%;">
                <logs ref="reflog" :type__like="routeName" :task_name="task_name" />
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
import logs from '@/views/setting/timerTask/components/logs.vue'
import { TimerTaskListGet, TimerTaskConfigListGet, TimerTaskConfigListPost, TimerTaskPkPost, TimerTaskPkDelete } from '@/api/setting/timerTask/index.js'
import { ref, reactive, onMounted, onActivated } from 'vue'
import { loadingStore, tabsBarStore, loginInfoStore } from '@/stores/index.js'
import { tabsIsAdd } from '@/utils/tabs.js'
import { useRouter, useRoute } from 'vue-router'
// 顶部菜单数据
const breadcrumbDataList = tabsBarStore()
const loginInfoStoreData = loginInfoStore()
const route = useRouter()
const routeName = useRoute().name
const loading = loadingStore()
const timerConfig = reactive({
    id: "",
    time: 5,
    status: false
})
let tableListData = ref([])
let drawer = ref(false)
let reflog = ref(null)
let orderTypeList = ref([
    { value: 1, label: '基础数据' },
    { value: 2, label: '业务单据' },
    { value: '', label: '全部' }
])
let task_name = ref('')
let orderType = ref('')

let tableObjData = reactive({
    name__like: '',
    type__like: '',

    page: 1,
    total: 0,
    has_next: false,
    has_prev: false,
    pages: 0,
    pageSize: 30
})

onMounted(() => {
    if (routeName != 'timertask') {
        tableObjData.type__like = routeName
    }
    timerTaskConfigEv()
})
onActivated(() => {

})
const addEv = () => {
    tabsTaskPushEv()
}
// 查询数据
const getEv = async (msg) => {
    loading.loading = true
    if (orderType.value !== '') {
        tableObjData.order_type = orderType.value
    } else {
        delete tableObjData['order_type']
    }
    try {
        let arr_data = await TimerTaskListGet(tableObjData)
        if (arr_data.status != 200) {
            return
        }
        if (msg == true) {
            ElMessage.success('查询成功')
        }
        tableListData.value = arr_data.data.result.data
        tableObjData.total = arr_data.data.result.total
        tableObjData.has_next = arr_data.data.result.has_next
        tableObjData.has_prev = arr_data.data.result.has_prev
        tableObjData.pages = arr_data.data.result.pages
        // tableObjData.pageSize = arr_data.data.result.pageSizes

    } catch (error) {
        ElMessage.error('查询接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}

const updateSelRowEv = async (rowId) => {
    console.log('跳转到新增推送任务')
    const val = {
        router: '/setting/timertaskedit',
        title: '编辑推送任务'
    }
    sessionStorage.setItem("timertaskedit_id", rowId)
    loginInfoStoreData.menuActive = val.router
    route.push({ path: val.router })
    // 判断是否增加顶部菜单导航
    tabsIsAdd(val, breadcrumbDataList)
}

const logItmEv = async (rowName) => {
    task_name.value = rowName
    drawer.value = true

}
const openedDrawerEv = async () => {
    reflog.value.getEv(false)
}

// 任务状态启用或者停止
const timerTaskStatusEv = async (id) => {
    const message = await ElMessageBox.confirm('确定停止此任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning ',
        confirmButtonClass: 'confirm-suer',
        cancelButtonClass: 'confirm-cancel',
        roundButton: true,
    }).catch((err) => err)

    if (message === 'confirm') {
        loading.loading = true
        try {
            let arr_data = await TimerTaskPkPost(id)
            if (arr_data.status != 200) {
                return
            }
            await getEv(false)
            ElMessage.success('启动成功')
        } catch (error) {
            ElMessage.error('启动接口请求失败' + error)
        } finally {
            loading.loading = false
        }
    }

}

// 查询定时任务配置
const timerTaskConfigEv = async () => {

    loading.loading = true
    try {
        let arr_data = await TimerTaskConfigListGet()
        if (arr_data.status != 200) {
            return
        }
        await getEv(false)
        timerConfig.id = arr_data.data.result.id
        timerConfig.time = arr_data.data.result.time
        timerConfig.status = arr_data.data.result.status

    } catch (error) {
        ElMessage.error('启动接口请求失败' + error)
    } finally {
        loading.loading = false
    }

}

// 定时任务配置编辑
const timerTaskConfigEdit = async () => {

    const message = await ElMessageBox.confirm('确定此操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning ',
        confirmButtonClass: 'confirm-suer',
        cancelButtonClass: 'confirm-cancel',
        roundButton: true,
    }).catch((err) => err)
    if (message === 'confirm') {
        loading.loading = true
        // timerConfig.status = !timerConfig.status
        timerConfig.status = true
        try {
            let arr_data = await TimerTaskConfigListPost(timerConfig)
            if (arr_data.status != 200) {
                return
            }
            await timerTaskConfigEv()

        } catch (error) {
            ElMessage.error('启动接口请求失败' + error)
        } finally {
            loading.loading = false
        }
    }
}

// 跳转到新增推送任务
const tabsTaskPushEv = () => {
    console.log('跳转到新增推送任务')
    const val = {
        router: '/setting/timertaskadd',
        title: '新增推送任务'
    }
    loginInfoStoreData.menuActive = val.router
    route.push({ path: val.router })
    // 判断是否增加顶部菜单导航
    tabsIsAdd(val, breadcrumbDataList)
}

</script>

<style lang='less' scoped>
.tr {
    height: 100%;
}

.tr-top {
    height: var(--tr-top-height);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
        display: flex;
        align-items: center;
    }

    .right {
        display: flex;
        align-items: center;
    }

    .itm {
        padding-right: 4px;
        box-sizing: border-box;
    }
}

.table-content {
    height: calc(100% - var(--tr-top-height) - var(--tr-page-height));
}
</style>